<template>
    <el-container>
        <el-header class="header_section">
            <el-row type="flex" justify="start" align="middle" style="height: 100%; margin-left:10px">
                <el-col class="el-col" :span="6" style="text-align:left;">
                    <span style="font-family:'黑体';font-size:28px;font-weight:1000;">
                        代码分析系统
                    </span>
                </el-col>

                <el-col class="el-col" :span="2" :offset="14">
                    <el-popover v-show="resultDisabled"
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        content="请上传文件并等待分析结果！">
                        <button  slot="reference" v-show="uploadDisabled" class="barButton" @click="dialogTableVisible = true" :disabled="uploadDisabled">
                            <upload theme="outline" size="22" fill="#b32828" :strokeWidth="4"/>
                            <br>
                            <span style="font-size: 1rem">上传文件</span>
                        </button>
                    </el-popover>

                    <button v-show="!uploadDisabled" class="barButton" @click="dialogTableVisible = true" :disabled="uploadDisabled">
                        <upload theme="outline" size="22" fill="#b32828" :strokeWidth="4"/>
                        <br>
                        <span style="font-size: 1rem">上传文件</span>
                    </button>
                </el-col>

                <el-col class="el-col" :span="2">
                    <el-popover v-show="resultDisabled"
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        content="请上传文件并等待分析结果！">
                        <button slot="reference" class="barButton" @click="drawerVisi = true" :disabled="resultDisabled">
                            <download theme="outline" size="22" fill="#b32828" :strokeWidth="4"/>
                            <br>
                            <span style="font-size: 1rem">获取结果</span>
                        </button>
                    </el-popover>

                    <button v-show="!resultDisabled" class="barButton" @click="drawerVisi = true" :disabled="resultDisabled">
                        <download theme="outline" size="22" fill="#b32828" :strokeWidth="4"/>
                        <br>
                        <span style="font-size: 1rem">获取结果</span>
                    </button>
                </el-col>
            </el-row>
        </el-header>

        <el-drawer :with-header="false" :visible.sync="drawerVisi" :before-close="handleClose">
            <el-descriptions class="el-my-descriptions" title="分析结果" :colon="false" :column="1" style="padding: 5% 5% 5% 5%">
                <template slot="extra">
                    <el-link type="primary">一键导出</el-link>
                </template>
                <el-descriptions-item label="上传数据量" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">1</el-descriptions-item>
                <el-descriptions-item label="成功建模数" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">1</el-descriptions-item>
                <el-descriptions-item label="类的总数量" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">1</el-descriptions-item>
                <el-descriptions-item label="方法总数量" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">1</el-descriptions-item>

                <el-descriptions-item label="数量分类" :contentStyle="{'display':'block', 'text-align':'right', 'padding-bottom': '10px'}">
                    点击查看详情
                    <i v-if="!showDetailNumber" class="el-icon-arrow-down" @click="showDetailNumber = true" style=":hover {cursor:pointer;}"></i>
                    <i v-else class="el-icon-arrow-up" @click="showDetailNumber = false" style=":hover {cursor:pointer;}"></i>
                    
                </el-descriptions-item>

                <el-descriptions-item v-if="showDetailNumber" >
                    <el-descriptions :colon="false" :with-header="false" :column="1">
                        <el-descriptions-item label="Java" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                        <el-descriptions-item label="JavaScript" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                        <el-descriptions-item label="Ruby" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                        <el-descriptions-item label="Python" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                        <el-descriptions-item label="Cpp" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                        <el-descriptions-item label="Go" :contentStyle="{'display':'block', 'text-align':'right'}">1</el-descriptions-item>
                    </el-descriptions>
                </el-descriptions-item>
                

                <el-descriptions-item v-if="showSelectLanguageItemOrNot" label="下载格式" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">
                    <!-- <el-checkbox-group v-model="checkList">
                        <el-checkbox label="json"></el-checkbox>
                        <el-checkbox label="dot"></el-checkbox>
                        <el-checkbox label="gml"></el-checkbox>
                    </el-checkbox-group> -->
                    <el-radio-group v-model="radio">
                        <el-radio :label="0">JSON</el-radio>
                        <el-radio :label="1">DOT</el-radio>
                        <el-radio :label="2">GML</el-radio>
                    </el-radio-group>
                </el-descriptions-item>

                <el-descriptions-item label="文件下载" :contentStyle="{'display':'block', 'text-align':'center', 'padding-bottom': '10px'}">
                    <el-button @click="getDataResult" type="info" round size="mini">基本信息</el-button>
                    <el-button @click="getGraphResult" type="info" round size="mini" style="margin-left: 10%">数据结果</el-button>
                </el-descriptions-item>
            </el-descriptions>
        </el-drawer>

        <el-main class="main_section">
            <div class="box" ref="box">
                <div class="left">
                    <div class="tool_bar">
                        <div class="left_section">
                            <el-dropdown trigger="click" @command="onThemeChange">
                                <theme class="toolButton" theme="outline" size="24" fill="#333"/>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="bright">
                                        <sun-one theme="outline" size="18" fill="#333" strokeWidth="4"/>
                                        Bright
                                    </el-dropdown-item>
                                    <el-dropdown-item command="warm">
                                        <sunny theme="outline" size="18" fill="#333" strokeWidth="4"/>
                                        Warm
                                    </el-dropdown-item>
                                    <el-dropdown-item command="dark">
                                        <moon theme="outline" size="18" fill="#333" strokeWidth="4"/>
                                        Dark
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>

                            <el-dropdown trigger="click" @command="handleFontItemClick">
                                <text-style-one class="toolButton" theme="outline" size="24" fill="#333" strokeWidth="4"/>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                    v-for="item in fontItems"
                                    :key="item.command"
                                    :command="item.command"
                                    >
                                    {{ item.command }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>

                            <save class="toolButton" theme="outline" size="24" fill="#333" strokeWidth="4" @click="saveContent"/>
                            <!-- <save class="toolButton" theme="outline" size="24" fill="#333" strokeWidth="4" @click="recoverContent"/> -->
                        </div>
                        
                        <div class="spacer"></div>

                        <div class="right_section">
                            <el-select v-model="lang" @change="selectLanguage()" size="small" style="width: 120px;">
                                <el-option
                                v-for="item in LanguageType"
                                :key="item.lang"
                                :label="item.label"
                                :value="item.lang">
                                </el-option>
                            </el-select>

                            <el-button id="resetCodeButton" type="primary" @click="resetCode">
                                重置
                            </el-button>

                            <el-button id="submitCodeButton" type="primary" @click="submitCode">
                                提交
                            </el-button>
                        </div>
                    </div>

                    <editor ref='myEditor' v-model="content" @init="editorInit" 
                        lang="java" :options="editorOptions" theme="solarized_light" 
                        width="100%">
                    </editor>
                </div>

                <div class="resize" title="收缩侧边栏"></div>

                <div class="mid">

                    <el-tabs v-model="activeType" type="card" @tab-click="handleClick" style="margin:auto 2% auto 2%" >
                        <el-tab-pane 
                        v-for="tab in DiagramType"
                        :key="tab.type"
                        :label="tab.label"
                        :name="tab.label"
                        ></el-tab-pane>
                    </el-tabs>
                    
                    <div id="astDiagramDiv" style="display: none; width: 100%; height: 90%; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;"></div>
                    <div id="cfgDiagramDiv" style="display: none; width: 100%; height: 90%; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;"></div>
                    <div id="cdgDiagramDiv" style="display: none; width: 100%; height: 90%; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;"></div>
                    <div id="ddgDiagramDiv" style="display: none; width: 100%; height: 90%; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); cursor: auto;"></div>
                </div>
            </div>
        </el-main>

        <el-dialog title="上传文件" :visible.sync="dialogTableVisible" :close-on-click-modal="false" width="35%" center>
            <el-form ref="form" :model="form" label-width="80px" size="small" label-position="left" :rules="rules" style="padding: 0% 8%;">
                <el-form-item label="项目名" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="上传类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择上传文件类型" style="width: 100%">
                        <el-option
                        v-for="item in UploadType"
                        :key="item.type"
                        :label="item.label"
                        :value="item.type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-show="showSelectLanguageItemOrNot" label="分析语言" prop="lang">
                    <el-select v-model="form.lang" placeholder="请选择语言" style="width: 100%">
                        <el-option
                        v-for="item in LanguageType"
                        :key="item.lang"
                        :label="item.label"
                        :value="item.lang">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="desc">
                    <el-input v-model="form.desc"></el-input>
                </el-form-item>
                <el-form-item ref="upload_attach_item" label="上传文件" prop="file" style="width: 100%;">
                    <el-upload 
                        v-model="form.file"
                        ref="upload_attach"
                        class="uploadContainer"
                        action=""
                        multiple
                        accept=""
                        :limit="1"
                        :on-change="changFile"
                        :on-exceed="handleExceed"
                        :on-remove="removeFile"
                        :file-list="fileList"
                        :auto-upload="false"
                        :http-request="uploadSectionFile">
                        <el-button size="mini" style="width: 100%;" round>选择文件</el-button>
                        <div slot="tip" class="el-upload__tip">
                            <el-tooltip placement="bottom">
                            <div slot="content">
                                JsonL数据集可包含多种语言源代码<br/>
                                ps:<br/>
                                {"code": "int a = 10", "lang": "java"}<br/>
                                {"code": "int b = 20", "lang": "python"}
                            </div>
                            <span>悬浮此处以查看文件格式！</span>
                            </el-tooltip>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <div style="text-align: center;">
                <i class="el-icon-warning" style="margin-right: 5px;"></i>
                <strong>注意：1.上传文件后会将上一次分析结果覆盖！2.请查看文件格式！</strong>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onSubmit('form'); dialogTableVisible = false" size="medium" style="margin-right: 3%;" round>确认</el-button>
                <el-button type="primary" @click="dialogTableVisible = false" size="medium" round>取消</el-button>
            </span>

        </el-dialog>
    </el-container>
</template>

<script>
import '@icon-park/vue/styles/index.css' // 引入样式表,整个项目只需要一次
import {
    Upload,
    Download,
    SunOne,
    Sunny,
    Moon,
    Save,
    TextStyleOne,
    Theme
} from '@icon-park/vue' // 引入icons
import { astInit } from '../common/gojsDiagram/ast'
import { cfgInit } from '../common/gojsDiagram/cfg'
import { cdgInit } from '../common/gojsDiagram/cdg'
import { ddgInit } from '../common/gojsDiagram/ddg'
import { dragControllerDiv } from '../common/dragController'
import { formatDiagramData } from '../common/utils'

import { UploadType, LanguageType, AnalysisState, DiagramType, LangDemo, ExportType, ExportFormat } from '../common/enums'

import {
    submitEditContent,
    saveCode,
    recoverCode,
    submitFileForm,
    getResult,
    exportResult
}
from "@/network/home";

export default {
    components: {
        editor: require('vue2-ace-editor'), // 导入vue2-ace-editor作为组件
        Upload,
        Download,
        Theme,
        SunOne,
        Sunny,
        Moon,
        Save,
        TextStyleOne
    },
    computed: {
        showSelectLanguageItemOrNot() {
            console.log("showSelectLanguageItemOrNot: ", this.form.type == UploadType[1].type)
            return this.form.type == UploadType[1].type;
        }
    },
    watch: {
        content: {
            handler(newContent, oldContent) {
                // 监听最新值与暂存值的差值是否达到要求，若达到要求则保存！并更新暂存值
                if (Math.abs(newContent.length - this.cacheContent.length) > 50) {
                    this.cacheContent = newContent;
                    this.saveContent();
                }
            },
	}
    },
    data(){
        var validateAttach = (rule, value, callback) => {
                console.log('校验fileList上传文件长度', this.fileList.length);
                if (this.fileList.length == 0) {
                    callback(new Error('请上传文件'));
                } else {
                    callback();
                }
            };
            /*以上是弹窗所需要的代码*/

        return {
            UploadType,
            LanguageType,
            AnalysisState,
            DiagramType,
            LangDemo,
            ExportType,
            ExportFormat,
            lang: 'Java',

            resultDisabled: false, // 默认还没有结果可以获取，设置为不可点击
            uploadDisabled: false, // 分析是否完成，初始化为完成状态，当上传文件后，设置为false，等分析完成后设置为true

            checkList: [],

            showDetailNumber: false,
            drawerVisi: false,

            activeType: 'ast',
            radio: 0,
            timeId: '',

            fontItems: [
                { command: "16" },
                { command: "17" },
                { command: "18" },
                { command: "19" },
                { command: "20" },
                { command: "21" },
                { command: "22" },
                { command: "23" },
                { command: "24" },
            ],

            astDiagram: null,
            cfgDiagram: null,
            cdgDiagram: null,
            ddgDiagram: null,

            diagramData: [],

            editorOptions: {
                showPrintMargin: false,
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true, /*自动补全*/
                useWorker: false, // 禁止错误提示
                // highlightGutterLine: false, // 这个使得当前行在行号区的高亮消失
                fontSize: 16,
            },

            content: "",
            cacheContent: "",

            fontSize: 16,

            // 文件上传
            dialogTableVisible: false,
            form: {
                name: '',
                lang: 'Java',
                type: 1,
                desc: '',
                file: null
            },
            fileList: [],
            rules: {
                // 对上传的文件进行验证：必须上传，否则弹出“请上传文件”
                file: [{ validator: validateAttach, trigger: 'change' }],
            },

            timer: null
        }
        
    },
    mounted(){
        // 根据窗口大小更改fontSize，使得1rem能够根据窗口大小实现自适应（使用在bar的两个button）
        (function(doc,win){
            // console.log(getComputedStyle(window.document.documentElement)['font-size'])
            var docEI = doc.documentElement,
            resizeEvt = 'orientationchange' in window?'orientataionchange':'resize',
            recalc = function(){
                var clientWidth = docEI.clientWidth;
                if(!clientWidth) return;
                //16是字体大小，1536是开发时浏览器窗口的宽度，等比计算
                docEI.style.fontSize = 16*(clientWidth/1536)+'px';
                console.log(docEI.style.fontSize)
            }

            if(!doc.addEventListener) return;
            win.addEventListener(resizeEvt, recalc, false);
            doc.addEventListener('DOMContentLoaded', recalc, false);
        })(document,window);

        // 拖动条控制方法
        dragControllerDiv();

        this.setLangDemo();


        // //定时任务方法
        // this.$nextTick(() => {
        //     this.timeId = setInterval(this.saveContent, 5000);
        // });
    },
    methods: {
        // 恢复内容
        recoverContent() {
            recoverCode()
            .then(res => {
                this.content = res.data;
            })
            .catch(error => {
                
            });
        },
        // 关闭
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        },
        // 重置代码
        resetCode() {
            // this.content = "";
            this.setLangDemo();
            this.resetDiagramData();
        },
        resetDiagramData() {
            this.diagramData = [];

            if (this.astDiagram)
                this.astDiagram.div = null;
            if (this.cfgDiagram)
                this.cfgDiagram.div = null;
            if (this.cdgDiagram)
                this.cdgDiagram.div = null;
            if (this.ddgDiagram)
                this.ddgDiagram.div = null;

            this.astDiagram = null;
            this.cfgDiagram = null;
            this.cdgDiagram = null;
            this.ddgDiagram = null;
            document.getElementById("astDiagramDiv").style.display = "none";
            document.getElementById("cfgDiagramDiv").style.display = "none";
            document.getElementById("cdgDiagramDiv").style.display = "none";
            document.getElementById("ddgDiagramDiv").style.display = "none";

            // if (this.astDiagram) {
            //     var divElement = document.createElement("astDiagramDiv");
            //     // 设置 div 的 id 和样式属性
            //     divElement.id = "astDiagramDiv";
            //     divElement.style.display = "none";
            //     divElement.style.width = "100%";
            //     divElement.style.height = "90%";
            //     divElement.style.webkitTapHighlightColor = "rgba(255, 255, 255, 0)";
            //     divElement.style.cursor = "auto";

            //     // 将 div 元素添加到文档中的某个容器元素中，例如 body
            //     document.body.appendChild(divElement);

            //     this.astDiagram.div = null;
            // }


            // if (this.cfgDiagram)
            //     this.cfgDiagram.clear();
            // if (this.cdgDiagram)
            //     this.cdgDiagram.clear();
            // if (this.ddgDiagram)
            //     this.ddgDiagram.clear();
        },
        // 利用cookie等内容保存
        saveContent() {
            saveCode(this.content, this.lang)
                .then(res => {
                    
                })
                .catch(error => {

                });
            
        },
        // 处理更换主题
        onThemeChange(command) {
            const editor = this.$refs.myEditor.editor;
            if (command == "bright") {
                editor.setTheme("ace/theme/chrome");
            } else if (command == "warm") {
                editor.setTheme("ace/theme/solarized_light");
            } else if (command == "dark") {
                editor.setTheme("ace/theme/monokai");
            }
        },
        // 上传文件
        uploadFile() {
            console.log("Xxx")
            


        },
        /*以下是弹窗的代码*/
        changFile(file, fileList) {
            this.fileList = fileList;
            this.$refs.form.validateField('file');
        },
        removeFile(file, fileList) {
            //删除上传的文件后会触发
            this.fileList = fileList;
            this.$refs.form.validateField('file');
        },
        handleExceed(files, fileList) {
            //文件上传发生错误时触发
            this.$message.warning(`当前限制最多选择 1 个文件`);
        },
        //交互的部分主要是onSubmit和uploadSectionFile这两个函数
        onSubmit(formName) {
            // 校验合法性
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.$refs.upload_attach.submit(); // 触发调用uploadSectionFile，拿到param参数里面的FileList
                    this.$message({
                        type: 'success',
                        message: '上传成功!'
                    });
                } else {
                    this.$message({
                        message: '请填写完整信息再后提交',
                        type: 'error'
                    });
                    return false;
                }
            });
        },
        uploadSectionFile(param) {
            //整理上传参数
            var formData = new FormData();
            //获取文件
            this.form.file = param.file;
            //将form表单的值全部赋给formdata传给后台
            for (var key in this.form) {
                formData.append(key, this.form[key]);
            }
            submitFileForm(formData)
                .then(res => {
                    console.log(res)
                    if (res.code === 0) {
                        // this.$message.success(res.msg);
                        // console.log("提交文件的返回结果为", res);
                        this.uploadDisabled = true;
                        // this.uploadDisabled = true;
                        this.$store.commit("SET_FILEID", res.data);
                        window.timer = setInterval(() => {
                            setTimeout(this.getResultByPolling(), 0)
                        }, 5000)
                    }
                })
                .catch(error => {
                    console.log(error)
                    // 处理 Promise 的拒绝原因
                });
        },
        // 轮询
        getResultByPolling() {
            getResult(this.$store.getters.fileID).then(res => {
                console.log(res)
                // 分析完成
                if (res.data.state == AnalysisState[3].state) {
                    this.resultDisabled = false;
                    this.uploadDisabled = false;
                    this.$message.success("分析完成，请获取结果！");
                    // 停止轮询
                    clearInterval(timer)
                }
            }).catch(error => {
                this.$message.error(error)
            })
        },
        handleClick() {
            if (!this.diagramData.length) {
                this.$message.info("请提交编辑的代码，等待分析结果！");
                return;
            }
            console.log(this.activeType, "astDiagram", this.diagramData[0].nodes, this.diagramData[0].edges)
            if (this.activeType === "AST") {
                document.getElementById("astDiagramDiv").style.display = "";
                document.getElementById("cfgDiagramDiv").style.display = "none";
                document.getElementById("cdgDiagramDiv").style.display = "none";
                document.getElementById("ddgDiagramDiv").style.display = "none";
                if (!this.astDiagram) {
                    // if (!this.diagramData[0]) {
                    //     this.$message.error(this.activeType + " 分析失败")
                    //     return ;
                    // }

                    this.astDiagram = astInit(this.diagramData[0].nodes, this.diagramData[0].edges);
                }
                this.astDiagram.model = new go.GraphLinksModel(this.diagramData[0].nodes, this.diagramData[0].edges);
            } else if (this.activeType === "CFG") {
                document.getElementById("astDiagramDiv").style.display = "none";
                document.getElementById("cfgDiagramDiv").style.display = "";
                document.getElementById("cdgDiagramDiv").style.display = "none";
                document.getElementById("ddgDiagramDiv").style.display = "none";
                if (!this.cfgDiagram) {
                    // if (!this.diagramData[1] || !this.diagramData[1].nodes || this.diagramData[1].nodes.length == 0) {
                    //     this.$message.error(this.activeType + " 分析失败")
                    //     return ;
                    // }

                    this.cfgDiagram = cfgInit(this.diagramData[1].nodes, this.diagramData[1].edges);
                }
                this.astDiagram.model = new go.GraphLinksModel(this.diagramData[0].nodes, this.diagramData[0].edges);
            } else if (this.activeType === "CDG") {
                document.getElementById("astDiagramDiv").style.display = "none";
                document.getElementById("cfgDiagramDiv").style.display = "none";
                document.getElementById("cdgDiagramDiv").style.display = "";
                document.getElementById("ddgDiagramDiv").style.display = "none";
                if (!this.cdgDiagram) {
                    // if (!this.diagramData[2] || !this.diagramData[2].nodes) {
                    //     this.$message.error(this.activeType + " 分析失败")
                    //     return ;
                    // }

                    this.cdgDiagram = cdgInit(this.diagramData[2].nodes, this.diagramData[2].edges || this.diagramData[2].nodes.length == 0);
                }
                this.astDiagram.model = new go.GraphLinksModel(this.diagramData[0].nodes, this.diagramData[0].edges);
            } else if (this.activeType === "DDG") {
                document.getElementById("astDiagramDiv").style.display = "none";
                document.getElementById("cfgDiagramDiv").style.display = "none";
                document.getElementById("cdgDiagramDiv").style.display = "none";
                document.getElementById("ddgDiagramDiv").style.display = "";
                if (!this.ddgDiagram) {
                    // if (!this.diagramData[3] || !this.diagramData[3].nodes) {
                    //     this.$message.error(this.activeType + " 分析失败")
                    //     return ;
                    // }
                    this.ddgDiagram = ddgInit(this.diagramData[3].nodes, this.diagramData[3].edges || this.diagramData[3].nodes.length == 0);
                }
                this.astDiagram.model = new go.GraphLinksModel(this.diagramData[0].nodes, this.diagramData[0].edges);
            }
        },
        // 处理vue2-ace-editor的相关函数
        // 初始化
        editorInit() {
            require('brace/ext/language_tools') //language extension prerequsite...
            // language  
            require('brace/mode/java')             
            require('brace/mode/javascript')    
            require('brace/mode/ruby')
            require('brace/mode/python')
            require('brace/mode/c_cpp')
            require('brace/mode/golang')
            // theme
            require('brace/theme/chrome') // Bright
            require('brace/theme/solarized_light') // Warm
            require('brace/theme/monokai') // Dark
            // snippet
            require('brace/snippets/java')
            require('brace/snippets/javascript')
            require('brace/snippets/ruby') 
            require('brace/snippets/python')
            require('brace/snippets/c_cpp') 
            require('brace/snippets/golang')
            // error_maker
            require('brace/ext/error_marker'); // 加载错误检查规则
        },
        // 处理语言选择
        selectLanguage() {
            const editor = this.$refs.myEditor.editor
            editor.session.setMode("ace/mode/" + this.value)

            this.setLangDemo();
        },
        // 处理字体大小变化
        handleFontItemClick(command) {
            const editor = this.$refs.myEditor.editor;
            editor.setFontSize(command + "px")
        },
        // 提交
        submitCode() {
            console.log(this.content)
            let formData = new FormData();
            formData.append("lang", this.lang);
            formData.append("content", this.content);
            submitEditContent(formData)
                .then ( res => {
                    if (res.code == 0) {
                        // 重置图表
                        this.resetDiagramData();
                        this.$message.success(res.msg);
                        console.log("提交编辑内容的返回结果为",res);
                        var tempData = res.data;
                        // this.diagramData = res.data;
                        // console.log("res.data: ", res.data)
                        tempData.forEach(diagram => {
                            // console.log(diagram)
                            diagram = JSON.parse(diagram)
                            if (diagram != null && diagram.nodes != null) {
                                this.diagramData.push(formatDiagramData(diagram))
                                // console.log(this.diagramData)
                            }
                            
                        })
                    }
                    // 提交前最好有个弹窗确认？
                    // 分析后应该也有弹窗提醒？
                })
                .catch(error => {
                    console.log(error)
                // 处理 Promise 的拒绝原因
                })
            this.saveContent();
        },
        setLangDemo() {
            switch (this.lang) {
                case "Cpp":
                    this.content = this.LangDemo[0].demo
                    break
                case "JavaScript":
                    this.content = this.LangDemo[1].demo
                    break
                case "Java":
                    this.content = this.LangDemo[2].demo
                    break
                case "Python":
                    this.content = this.LangDemo[3].demo
                    break
                case "Golang":
                    this.content = this.LangDemo[4].demo
                    break
                case "Ruby":
                    this.content = this.LangDemo[5].demo
                    break

            }
        },
        isBlank(str) {
            if (str == null) return true;
            return /^\s*$/.test(str);
        },
        getGraphResult() {
            var fileId = this.$store.getters.fileID;
            var fileName;
            if (this.isBlank(this.form.name))
                fileName = fileId
            else
                fileName = form.name
    
            try {
                if (this.showSelectLanguageItemOrNot) {
                    // 上传单一语言源代码
                    exportResult(fileId, this.ExportType[0].type, this.ExportFormat[this.radio].format).then(res => {
                        console.log("res is :", res)
                        // 在获取响应后创建 Blob 对象
                        const blob = new Blob([res], { type: 'application/octet-stream' });

                        // 创建一个 <a> 标签，并设置其属性，用于触发文件下载
                        const link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName + "-" + this.ExportFormat[this.radio].format + ".zip"; // 替换为实际的文件名
                        link.style.display = 'none';

                        // 将 <a> 标签添加到 DOM 并触发点击事件，开始下载
                        document.body.appendChild(link);
                        link.click();

                        // 清理
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(link.href);
                    }).catch(err => {
                        console.log(err);
                    });
                } else {
                    // 上传 jsonl 数据集
                    console.log(this.ExportType[2].type)
                    exportResult(fileId, this.ExportType[2].type).then(res => {
                        // 在获取响应后创建 Blob 对象
                        console.log("res.data", res)
                        const blob = new Blob([res], { type: 'application/jsonlines' });

                        // 创建一个 <a> 标签，并设置其属性，用于触发文件下载
                        const link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName + ".jsonl";
                        link.style.display = 'none';

                        // 将 <a> 标签添加到 DOM 并触发点击事件，开始下载
                        document.body.appendChild(link);
                        link.click();

                        // 清理
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(link.href);
                    }).catch(err => {
                        console.log(err);
                    });
                }
            } catch (error) {
                console.error('下载文件出错：', error);
            }
        },
        getDataResult() {

        }
    },
    created() {
        recoverCode()
            .then(res => {
                if (res.code != 0) {
                    // 获取失败
                    this.setLangDemo();
                } else {
                    // console.log("恢复代码", res)
                    // 获取成功
                    // 用恢复的代码
                    this.content = res.data.content;
                    this.lang = res.data.lang;
                }

            })
            .catch(error => {
                // 获取失败
                this.setLangDemo();
            });
    },
    beforeDestroy() {
    }
}
</script>


<style scoped lang="scss">
// 背景色
$header-background-color: grey;
$main-background-color: white;
// 占用高度
$header-height:  60px;
$main-height: calc(100vh - #{$header-height});

.el-col {
    height: 100% !important;
    //margin-left: 5px;
}
.header_section {
    background-color: $header-background-color;
    height: $header-height !important;
    padding: 0;
}
.barButton {
    background-color: $header-background-color;
    border: none;
    height: 100%;
    &:hover {
        cursor: pointer;
        background-color: darken($color: $header-background-color, $amount: 10%);
    }
}
.toolButton {
    &:hover {
        cursor: pointer;
    }
}
.tool_bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    white-space: nowrap; /* 不换行 */
    padding: 10px;
}
.left_section, .right_section {
    display: flex;
    gap: 15px; /* 按钮之间的间距 */
}
.spacer {
    flex: 1; /* 占用剩余空间 */
}
.main_section{
    background-color: $main-background-color;
    height: $main-height;
    padding: 0;
}
.box {
    width: 100%;
    height: 100%;
    overflow: hidden;
    // box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);
}
/*左侧div样式*/
.left {
    // margin-top: 1vh;
    width: 50%;   /*左侧初始化宽度*/   
    height: 100%;
    background: white;
    float: left;
}
/*拖拽区div样式*/
.resize {
    cursor: col-resize;
    float: left;
    position: relative;
    background-color: #d6d6d6;
    border-radius: 5px;
    width: 5px;
    height: 100%;
    background-size: cover;
    background-position: center;
    /*z-index: 99999;*/
    font-size: 32px;
    // color: white;
    text-align: center;

    /*拖拽区鼠标悬停样式*/
    &:hover {
        background-color: #221c1c;
    }
}
/*右侧div'样式*/
.mid {
    margin-top: 1vh;
    float: left;
    width: calc(50% - 10px);  /*右侧初始化宽度*/
    height: 100%;
    background: #fff;
    
}
#myDiagramDiv {
	background-color: #F8F8F8;
	// border: 1px solid #aaa;
}
::v-deep .el-upload{
    width: 100%;
}
::v-deep .el-upload .el-upload--text{
    width: 100%;
}
</style>


